package com.treasure.web.controller.corp.admin;

import com.treasure.common.enums.IdentitiesEnum;
import com.treasure.common.enums.LoginRouteEnum;
import com.treasure.common.exception.ServiceException;
import com.treasure.common.model.SessionUser;
import com.treasure.common.reponse.Response;
import com.treasure.infrastructure.model.po.CorpUserInfo;
import com.treasure.web.command.request.login.LoginRequest;
import com.treasure.web.service.LoginHelper;
import com.treasure.web.service.IAccountService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 管理员登录（企业管理后台）
 *
 * @author sunhongmin
 * @date 2023/9/10 10:32
 * @description 企业管理后台-登录
 */
@RestController
@RequestMapping("/treasure/corp/admin")
@RequiredArgsConstructor
public class CorpAdminLoginController extends LoginHelper {
    private final IAccountService accountService;

    /**
     * 用户登录
     *
     * @param loginRequest 登录信息
     * @return
     */
    @PostMapping("/login")
    public Response<?> corpAdminLogin(@Validated({LoginRequest.AdminLoginValiadate.class}) @RequestBody LoginRequest loginRequest, HttpServletResponse servletResponse) {
        // 理想情况下，企业管理员账户应该只有一个管理身份的企业信息
        List<CorpUserInfo> corpUserInfoList = accountService.login(loginRequest, LoginRouteEnum.ADMIN_LOGIN_ROUTE);
        if (corpUserInfoList.size() > 1) {
            throw new ServiceException("该账户同时属于两个及以上企业/高校主体的管理员，请选择主体后进行登录");
        }
        CorpUserInfo corpUserInfo = corpUserInfoList.stream().findFirst().orElse(new CorpUserInfo());
        if (BooleanUtils.isNotTrue(corpUserInfo.getHasAdmin())) {
            throw new ServiceException("该账户不具有企业/高校后台管理权限，请联系管理员");
        }
        String token = getToken(corpUserInfo);
        addCookie(servletResponse, token);
        SessionUser sessionUser = getSessionUserCache(corpUserInfo, IdentitiesEnum.CORP_ADMIN);
        putCache(token, sessionUser);
        return Response.success();
    }

    /**
     * 用户登出
     *
     * @return
     */
    @PostMapping("/logout")
    public Response<?> logout(HttpServletRequest servletRequest) {
        return tokenLogout(servletRequest);
    }

}
